<template>
  <div class="user-detail">
    <!-- <el-card class="card-header">
      <span>账号信息</span>
    </el-card> -->
    <div class="card-footer">
      <ul>
        <li>
          <span class="title" style="margin-right: 10px;">账户名：</span>
          <span class="user">{{ username }}</span>
          <el-divider style="color: #eee;" class="name"></el-divider>
        </li>
        <li v-show="isMain == 0">
          <span class="title">员工姓名：</span>
          <span class="user">{{ name }}</span>
          <el-divider style="color: #eee;"></el-divider>
        </li>
        <li v-show="isMain == 0">
          <span class="title">职位：</span>
          <span class="user">{{
            position == 1 ? "经理" : position == 2 ? "员工" : ""
          }}</span>
          <el-divider style="color: #eee;"></el-divider>
        </li>
        <li>
          <span class="title" style="margin-right: 10px;">手机号：</span>
          <span class="user">{{ phone }} </span>
          <el-button v-if="phone" type="primary" size="small" class="revise-btn" @click="handleUpdate">修改</el-button>
          <el-divider style="color: #eee;" class="phone"></el-divider>
        </li>
        <li>
          <span class="title">电子邮箱：</span>
          <span class="user">{{ email }}</span>
          <el-divider style="color: #eee;"></el-divider>
        </li>
        <li>
          <span class="title">帐号状态：</span>
          <span class="user">{{
            status == 200 ? "正常" : status == 500 ? "停用" : ""
          }}</span>
          <el-divider style="color: #eee;"></el-divider>
        </li>
        <li>
          <span class="title">创建日期：</span>
          <span class="user">{{ createDate }}</span>
          <el-divider style="color: #eee;" class="date"></el-divider>
        </li>
      </ul>
      <!-- <el-divider></el-divider> -->
      <div class="btn">
        <!-- <el-divider></el-divider> -->
        <el-button type="primary" @click="handleUpdatePwd" size="small">修改密码</el-button>
        <el-button type="primary" @click="handleLogout" size="small">退出登录</el-button>
      </div>
    </div>
    <!-- 修改手机号 -->
    <el-dialog title="修改手机号" :visible.sync="dialogVisible" :close-on-click-modal="false" width="30%"
      style="margin: 100px auto" @close="handlePhoneClose">
      <el-form :rules="rules" :model="formPhone" ref="formPhone">
        <el-form-item label="原手机号：" :label-width="formLabelWidth" style="margin-left: 10px;">
          <span>{{ phone }}</span>
        </el-form-item>
        <el-form-item label="验证码：" :label-width="formLabelWidth" prop="code">
          <el-input v-model="formPhone.code" auto-complete="off" @input="onInput()" @blur="codeBlur('old')"
            style="width: 130px; margin-right: 10px"></el-input>
          <el-button v-if="isShow" type="primary" @click="handleCode">发送验证码</el-button>
          <el-button v-else type="primary" class="code-btn code-btn0" plain>{{ count }}s后重试</el-button>
          <div style="
              color: red;
              margin-top: -7px;
              font-size: 1px;
              width: 132px;
              height: 1px;
            " v-if="message !== null">
            {{ "验证码有误，请重新输入" }}
          </div>
          <div v-else>{{ "" }}</div>
        </el-form-item>
      </el-form>
      <el-dialog title="修改手机号" :visible.sync="innerVisible" :close-on-click-modal="false" width="30%" :modal="false"
        style="margin: 100px auto" @close="handleNewPhoneClose">
        <el-form :rules="rules" :model="formNewPhone" ref="formNewPhone">
          <el-form-item label="新手机号：" :label-width="formLabelWidth" prop="newPhone" style="margin-left: 10px;">
            <el-input v-model="formNewPhone.newPhone" @input="onInput()" auto-complete="off"
              style="width: 130px; margin-right: 10px" maxlength="11"
              onKeypress="return(/[\d\.]/.test(String.fromCharCode(event.keyCode)))"></el-input>
          </el-form-item>
          <el-form-item label="验证码：" :label-width="formLabelWidth" prop="newCode">
            <el-input v-model="formNewPhone.newCode" auto-complete="off" @input="onInput()" @blur="codeBlur('new')"
              style="width: 130px; margin-right: 10px;margin-left: 10px;"></el-input>
            <el-button v-if="isNewShow" type="primary" @click="handleNewCode('formNewPhone')">发送验证码</el-button>
            <el-button v-else type="primary" class="code-btn code-btn0" plain>{{ newCount }}s后重试</el-button>
            <div style="
                color: red;
                margin-top: -7px;
                font-size: 1px;
                width: 132px;
                height: 1px;
              " v-if="newMessage !== null">
              {{ "验证码有误，请重新输入" }}
            </div>
            <div v-else>{{ "" }}</div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="handleUpdatePhone('formNewPhone')" size="small">确 定</el-button>
          <el-button @click="handleNewPhoneClose" class="resletBtn" size="small">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="handleClick('formPhone')" size="small">确 定</el-button>
        <el-button @click="handlePhoneClose" class="resletBtn" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog title="修改密码" :visible.sync="dialogVisiblePwd" width="20%" class="pwdDialog" @close="handlePwdClose">
      <el-form :rules="rules" :model="formPwd" ref="formPwd">
        <el-form-item label="原密码：" :label-width="formLabelWidth" prop="oldPwd">
          <el-input v-model="formPwd.oldPwd" type="password" @blur="passwordBlur"></el-input>
        </el-form-item>
        <el-form-item label="新密码：" :label-width="formLabelWidth" prop="newPwd">
          <el-input v-model="formPwd.newPwd"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="small" @click="handlePwd('formPwd')">确 定</el-button>
        <el-button class="resletBtn" size="small" @click="handlePwdClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  updatePhone,
  updatePwd,
  getTelcode,
  getCode,
  getInfo,
} from "@/api/login.js";
import { findPhone, findPassword } from "@/api/user.js";
import { mapGetters } from "vuex";
import { validatephonenumber, pwdCheck } from "@/utils/validate.js";
import { Message } from "element-ui";
export default {
  data() {
    return {
      innerVisible: false,
      dialogVisible: false,
      dialogVisiblePwd: false,
      value: "",
      formLabelWidth: "120px",
      username: "",
      name: "",
      position: "",
      phone: "",
      email: "",
      createDate: "",
      status: "",
      // isMain: "",
      count: 59,
      newCount: 59,
      isShow: true,
      isNewShow: true,
      isNewPhone: true,
      formPhone: {
        code: "",
      },
      formNewPhone: {
        newPhone: "",
        newCode: "",
      },
      formPwd: {
        oldPwd: "",
        newPwd: "",
      },
      rules: {
        newPhone: [
          { required: true, trigger: "blur", message: "请输入您的手机号" },
          { validator: validatephonenumber, trigger: "blur" },
        ],
        code: [
          { required: true, trigger: "blur", message: "请输入验证码" },
          {
            required: true,
            trigger: "blur",
            message: "验证码有误，请重新输入",
          },
        ],
        newCode: [
          {
            required: true,
            trigger: "blur",
            message: "请输入验证码",
          },
          {
            required: true,
            trigger: "blur",
            message: "验证码有误，请重新输入",
          },
        ],
        oldPwd: [{ required: true, trigger: "blur", message: "请输入密码" }],
        newPwd: [
          {
            required: true,
            trigger: "blur",
            message: "请输入新密码",
          },
          {
            validator: pwdCheck,
            trigger: "blur",
          },
        ],
      },
      setPwd: {},
      message: null,
      newMessage: null,
    };
  },
  computed: {
    ...mapGetters(["id", "isMain"]),
  },
  mounted() {
    // this.phone = this.$store.state.user.phone;
    getInfo({ id: this.id }).then((res) => {
      if (res.success) {
        this.username = res.result.username;
        // this.isMain = res.result.isMain;
        this.name = res.result.name;
        this.position = res.result.position;
        this.email = res.result.email;
        this.phone = res.result.phone;
        this.createDate = res.result.createDate;
        this.status = res.result.status;
      }
    });
  },
  methods: {
    onInput() {
      this.$forceUpdate();
    },
    //校验新手机号是否重复
    newPhoneBlur() {
      if (this.formNewPhone.newPhone && this.formNewPhone.newPhone.length > 0) {
        findPhone({ phone: this.formNewPhone.newPhone }).then((res) => {
          if (res.code == 3004) {
            Message({
              message: res.message,
              type: "error",
            });
          }
        });
      }
    },
    //校验原密码是否重复
    passwordBlur() {
      if (this.formPwd.oldPwd && this.formPwd.oldPwd.length > 0) {
        findPassword({
          password: this.formPwd.oldPwd,
          userName: this.username,
        }).then((res) => {
          if (res.code == 500) {
            Message({
              message: res.message,
              type: "error",
            });
          }
        });
      }
    },
    //校验验证码
    codeBlur(type) {
      if (
        type == "old" &&
        this.formPhone.code &&
        this.formPhone.code.trim() &&
        this.formPhone.code.length > 0
      ) {
        getCode({ phone: this.phone, code: this.formPhone.code }).then(
          (res) => {
            if (res.code == 3007) {
              this.message = res.message;
              // Message({
              //   message: "验证码有误，请重新输入",
              //   type: "error",
              // });
            }
          }
        );
      } else {
        this.message = null;
      }
      if (
        type == "new" &&
        this.formNewPhone.newCode &&
        this.formNewPhone.newCode.trim() &&
        this.formNewPhone.newCode.length > 0
      ) {
        getCode({
          phone: this.formNewPhone.newPhone,
          code: this.formNewPhone.newCode,
        }).then((res) => {
          if (res.code == 3007) {
            this.newMessage = res.message;
            // Message({
            //   message: "验证码有误，请重新输入",
            //   type: "error",
            // });
          }
        });
      } else {
        this.newMessage = null;
      }
    },

    //修改密码
    handlePwd(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          let password = this.formPwd.oldPwd;
          let newPassword = this.formPwd.newPwd;
          updatePwd({ password, newPassword }).then((res) => {
            if (res.success) {
              // this.$message.success("修改密码成功，确定退出系统吗？");
              this.dialogVisiblePwd = false;
            }
            this.handlePwdLogout();
          });
        }
      });
    },
    //获取验证码
    handleCode() {
      let lock = false;
      // 调验证码的接口
      getTelcode(this.phone)
        .then((res) => {
          if (res.code == 3008) {
            Message({
              message: res.message,
              type: "error",
            });
          }
          if (res.code == 200) {
            //验证码倒计时
            lock = true;
            this.vaTime();
            this.$message.success(res.message);
          }
        })
        .finally(() => {
          lock = false;
        });
    },
    handleNewCode() {
      let lock = false;
      if (this.formNewPhone.newPhone !== this.phone) {
        if (
          this.formNewPhone.newPhone &&
          this.formNewPhone.newPhone.length > 0
        ) {
          findPhone({ phone: this.formNewPhone.newPhone }).then((res) => {
            if (res.code == 3004) {
              Message({
                message: res.message,
                type: "error",
                duration: 1000,
              });
            } else {
              // 调验证码的接口
              getTelcode(this.formNewPhone.newPhone)
                .then((res) => {
                  if (res.code == 3008) {
                    Message({
                      message: res.message,
                      type: "error",
                      duration: 1000,
                    });
                  }
                  if (res.code == 200) {
                    lock = true;
                    //验证码倒计时
                    this.newVaTime();
                    this.$message.success(res.message);
                  }
                })
                .finally(() => {
                  lock = false;
                });
            }
          });
        }
      } else {
        Message({
          message: "当前手机号与原手机号一致，请重新输入",
          type: "error",
          duration: 1000,
        });
      }
    },
    // 验证码倒计时
    vaTime() {
      this.count = 59;
      this.isShow = false;
      let timer = 0;
      timer = setInterval(() => {
        if (this.count > 0 && this.count <= 59) {
          this.count--;
        } else {
          this.isShow = true;
          clearInterval(timer);
          timer = 0;
        }
      }, 1000);
    },
    newVaTime() {
      this.newCount = 59;
      this.isNewShow = false;
      let timer = 0;
      timer = setInterval(() => {
        if (this.newCount > 0 && this.newCount <= 59) {
          this.newCount--;
        } else {
          this.isNewShow = true;
          clearInterval(timer);
          timer = 0;
        }
      }, 1000);
    },
    //退出登录
    handlePwdLogout() {
      this.$confirm("修改密码成功，确定退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/#/login";
          });
        })
        .catch(() => { });
    },
    handleLogout() {
      this.$confirm("确定退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/#/login";
          });
        })
        .catch(() => { });
    },
    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then((_) => {
    //       done();
    //       this.$refs.formPwd.clearValidate();
    //       this.$refs.formPhone.clearValidate();
    //       this.$refs.formNewPhone.clearValidate();
    //     })
    //     .catch((_) => {});
    // },
    //修改手机号
    handleUpdatePhone(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          getCode({
            phone: this.formNewPhone.newPhone,
            code: this.formNewPhone.newCode,
          }).then((res) => {
            if (res.code == 3007) {
              Message({
                message: "验证码有误，请重新输入",
                type: "error",
              });
            } else {
              this.isNewPhone = false;
              updatePhone({
                phone: this.formNewPhone.newPhone,
                userName: this.username,
              }).then((res) => {
                this.$message.success("手机号修改成功");
                this.phone = res.result.phone;
                this.innerVisible = false;
                // this.$router.push("/userDetail");
              });
            }
          });
        }
      });
    },
    //修改手机号
    handleClick(form) {
      // this.innerVisible = true;
      this.$refs[form].validate((valid) => {
        if (valid) {
          getCode({ phone: this.phone, code: this.formPhone.code }).then(
            (res) => {
              if (res.success) {
                this.innerVisible = true;
              } else {
                Message({
                  message: res.message,
                  type: "error",
                });
              }
            }
          );
        }
      });
    },
    //修改密码
    handleUpdatePwd() {
      this.dialogVisiblePwd = true;
    },
    handleUpdate() {
      this.dialogVisible = true;
      this.formPhone.code = "";
    },
    //关闭弹窗
    handlePhoneClose() {
      this.dialogVisible = false;
      this.formPhone = {};
      this.$refs.formPhone.clearValidate();
    },
    //关闭弹窗
    handleNewPhoneClose() {
      this.innerVisible = false;
      this.dialogVisible = false;
      this.formNewPhone = {};
      this.$refs.formNewPhone.clearValidate();
    },
    //关闭弹窗
    handlePwdClose() {
      this.dialogVisiblePwd = false;
      this.formPwd = {};
      this.isShow = true;
      this.$refs.formPwd.clearValidate();
    },
  },
};
</script>

<style lang="scss" scoped>
.user-detail {
  position: relative;
  height: calc(100% - 70px);
  .card-header {
    margin: 10px 36px 20px 28px;
    height: 60px;

    span {
      font-size: 18px;
      font-weight: bold;
      color: #000;
    }
  }

  .card-footer {
    margin-top: 40px;
    font-size: 16px;

    ul {
      padding: 0;

      li {
        list-style: none;
        font-size: 12px;
        font-weight: bold;
        color: #1A2035;

        .title {
          margin-left: 25px;
          font-size: 12px;
          font-weight: 600;

        }

        .user {
          font-weight: 400;
          margin-left: 50px;
          text-align: left;
          font-size: 12px;
        }


        .name.el-divider--horizontal {
          margin: 10px 0 5px 0 !important;
        }

        .phone.el-divider--horizontal {
          margin: 5px 0 10px 0 !important;
        }
        // .date.el-divider--horizontal{
        //   height: 0.5px;
        // }
        .revise-btn {
          margin-left: 20px;
          width: 50px;
        }

        ::v-deep.el-divider--horizontal {
          margin: 10px 0;
          // height: 1px !important;
        }
      }
    }

    .btn {
      // margin: 60px 0 120px 20px;
      position: absolute;
      bottom: 1%;
      left: 47%;
    }
  }

  .pwdDialog {
    .el-dialog__body {
      text-align: center;
    }

    ::v-deep.el-dialog:not(.is-fullscreen) {
      margin-top: 28vh !important;
    }

    // ::v-deep.el-form-item{
    //   margin-bottom: 5px;
    // }
  }
}
</style>